package com.wfm.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wfm.media.dto.MacVodDTO;
import com.wfm.media.entity.MacVod;
import com.wfm.media.entity.MacVodKey;
import com.wfm.media.mapper.MacVodMapper;
import com.wfm.media.service.MacVodService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MacVodServiceImpl extends ServiceImpl<MacVodMapper, MacVod> implements MacVodService {

    @Override
    public List<MacVodDTO> listAll() {
        List<MacVod> macVods = list();
        return macVods.stream().map(this::convertToDTO).collect(Collectors.toList());
    }

    @Override
    public boolean deleteByIds(Integer sourceId, Integer vodId) {
        LambdaQueryWrapper<MacVod> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MacVod::getSourceId, sourceId).eq(MacVod::getVodId, vodId);
        return remove(wrapper);
    }

    @Override
    public boolean add(MacVod macVod) {
        macVod.setVodTime(LocalDateTime.now());
        macVod.setVodTimeAdd((int)(System.currentTimeMillis() / 1000));
        return save(macVod);
    }

    @Override
    public MacVodDTO getByIds(Integer sourceId, Integer vodId) {
        LambdaQueryWrapper<MacVod> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MacVod::getSourceId, sourceId).eq(MacVod::getVodId, vodId);
        MacVod macVod = getOne(wrapper);
        return macVod != null ? convertToDTO(macVod) : null;
    }

    @Override
    public List<MacVodDTO> getBySourceId(Integer sourceId) {
        LambdaQueryWrapper<MacVod> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MacVod::getSourceId, sourceId);
        List<MacVod> macVods = list(wrapper);
        return macVods.stream().map(this::convertToDTO).collect(Collectors.toList());
    }

    @Override
    public boolean update(MacVod macVod) {
        macVod.setVodTime(LocalDateTime.now());
        LambdaQueryWrapper<MacVod> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MacVod::getSourceId, macVod.getSourceId())
              .eq(MacVod::getVodId, macVod.getVodId());
        return update(macVod, wrapper);
    }

    private MacVodDTO convertToDTO(MacVod macVod) {
        MacVodDTO dto = new MacVodDTO();
        dto.setSourceId(macVod.getSourceId());
        dto.setVodId(macVod.getVodId());
        dto.setVodName(macVod.getVodName());
        dto.setVodActor(macVod.getVodActor());
        return dto;
    }
}